<!--
	作者：515975089@qq.com
	时间：2018-10-31
	描述：合同管理
	应付员测试帐号：102631 111111
	订单号：8100028053 8100028554
-->
<template>
	<div class="m-view-contractManage m-window">
		<div class="m-condition">
			<el-row :gutter="10">
				<el-col :span="2" :offset="8">
					<el-radio v-model="billState" @change="changeradio" label="2">已审</el-radio>
				</el-col>
				<el-col :span="2">
					<el-radio v-model="billState" @change="changeradio" label="0">未审</el-radio>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="search(1)">查询</el-button>
				</el-col>
				<el-col :span="2" v-if="btnAuthList.indexOf('btn_contract_create')>-1">
					<el-button type="primary" @click="add" :disabled="btn_add_Disabled">新增</el-button>
				</el-col>
				<el-col :span="2" v-if="btnAuthList.indexOf('btn_contract_edit')>-1">
					<el-button type="primary" @click="edit" :disabled="btn_edit_Disabled||billState=='2'">编辑</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="viewDetail">查看</el-button>
				</el-col>
				<el-col :span="2" v-if="btnAuthList.indexOf('btn_contract_import')>-1">
					<el-button type="primary" @click="openImportDialog" :disabled="btn_edit_Disabled">导入</el-button>
				</el-col>
				<el-col :span="2" v-if="billState=='0'&&btnAuthList.indexOf('btn_contract_audit')>-1">
					<el-button type="primary" @click="reviewContract(2)" :disabled="btn_reuse_Disabled">审核</el-button>
				</el-col>
				<el-col :span="2" v-if="billState=='2'&&btnAuthList.indexOf('btn_contract_audit')>-1">
					<el-button type="primary" @click="reviewContract(0)" :disabled="btn_reuse_Disabled">弃审</el-button>
				</el-col>
			</el-row>
			<el-row :gutter="10">
				<el-form ref="ruleForm" label-width="70px" :inline-message="true" label-position="left">
					<el-col :span="7">
						<el-form-item label="公司" class="rightItem">
							<el-select
								v-model="selCompanyCode"
								placeholder="请选择公司"
								@change="companyChange"
								clearable
								ref="content"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item.companyCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="供应商" class="rightItem">
							<el-input
								placeholder="请选择供应商"
								v-model="selCusName"
								clearable
								@focus="showSupplierDialog"
								readonly
								@mouseenter.native="mouseEnter"
								@mouseleave.native="mounseLeave"
							>
								<el-button slot="append" icon="el-icon-search" @click="showSupplierDialog"></el-button>
								<span slot="suffix" @click="inputClearSon" class="m-cleanInput" v-show="inputClearBut">
									<i class="el-input_icon el-icon-circle-close el-input__clear"></i>
								</span>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="合同编号" class="rightItem">
							<el-input v-model="contractNo" placeholder="请输入合同编号" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
		</div>
		<div class="m-agTable m-bottom m-top2">
			<ag-grid-vue
				class="m-agTableContent ag-theme-balham"
				:gridOptions="gridOptions"
				:columnDefs="columnDefs"
				:rowData="rowData"
				v-loading="loading"
				rowSelection="multiple"
			></ag-grid-vue>
		</div>
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="currentPage"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</div>

		<el-dialog
			:title="title"
			:visible.sync="dialogVisible"
			width="50%"
			:before-close="handleClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			@opened="showCallback"
			v-if="dialogVisible"
		>
			<el-form
				:model="ruleForm"
				ref="ruleForm"
				label-width="100px"
				class="demo-ruleForm"
				:rules="rules"
			>
				<el-form-item label="合同编号" placeholder="合同编号" prop="contractNo" required>
					<el-input
						v-model.trim="ruleForm.contractNo"
						placeholder="请输入合同编号"
						clearable
						:disabled="inputDis"
					></el-input>
				</el-form-item>
				<el-form-item label="合同名称" placeholder="合同名称" prop="contractName" required>
					<el-input
						v-model.trim="ruleForm.contractName"
						placeholder="请输入合同名称"
						clearable
						:disabled="inputDis"
					></el-input>
				</el-form-item>
				<el-form-item label="公司" prop="selCompany" required>
					<el-select
						v-model="ruleForm.selCompany"
						required
						placeholder="请选择公司"
						@change="companyChange"
						:readonly="inputDis"
						:clearable="Ccommpany"
						:disabled="cdisabled"
						ref="content"
					>
						<el-option
							v-for="item in comOptions"
							:key="item.id"
							:label="item.companyName"
							:value="item.companyCode"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="供应商" prop="selCusName" required>
					<!-- <el-select  v-model="ruleForm.selCusName" placeholder="请选择供应商" :clearable="Csupplier" :disabled="sdisabled">
						<el-option v-for="item in cusOptions" :key="item.id" :label="item.supplierName" :value="item.id"></el-option>
					</el-select >-->
					<el-input
						placeholder="请选择供应商"
						required
						v-model="ruleForm.selCusName"
						clearable
						:readonly="inputDis"
						disabled
						@mouseenter.native="mouseEnter"
						@mouseleave.native="mounseLeave"
					>
						<el-button
							slot="append"
							icon="el-icon-search"
							@click="showSupplierDialogOther"
							v-show="!inputDis"
						></el-button>
						<span slot="suffix" @click="inputClearSon" class="m-cleanInput" v-show="inputClearBut">
							<i class="el-input_icon el-icon-circle-close el-input__clear"></i>
						</span>
					</el-input>
				</el-form-item>
				<el-form-item label="有效时间" placeholder="有效时间" prop="startDate" required>
					<el-col :span="12">
						<el-date-picker
							v-model="ruleForm.startDate"
							type="date"
							placeholder="开始日期"
							value-format="yyyy-MM-dd HH:mm:ss"
						></el-date-picker>
					</el-col>
					<el-col :span="12">
						<el-date-picker
							v-model="ruleForm.endDate"
							type="date"
							prop="endDate"
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
						></el-date-picker>
					</el-col>
				</el-form-item>
				<el-form-item label="添加附件" placeholder="添加附件">
					<!-- <el-upload
            class="upload-demo"
            :action="upload_url"
            :on-preview="handlePreview"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :limit="1"
            :file-list="fileList"
            :on-change="upload_change"
            :onSuccess="uploadSuccess"
            :before-upload="beforeAvatarUpload"
            :disabled="btn_upload_dis"
            :data="userInfo"
            accept=".pdf, .doc, .docx, .xls, .xlsx, .txt"
            ref="upload"
          >
					<!--:disabled="btn_upload_dis" @click="btn_upload"-->
					<!-- <el-button v-model="upload" size="small" type="primary">点击上传</el-button> -->
					<!--<div slot="tip" class="el-upload__tip">只能上传.txt/.pdf/.doc/.docx/.xls/.xlsx文件，且不超过20MB</div>-->
					<!-- </el-upload> -->
					<lessoUploader
						:baseUrl="baseUrl"
						:userInfo="userInfo"
						:deleteBtn="true"
						@fileError="fileError"
						@fileExceed="fileExceed"
						@fileAdded="fileAdded"
						@fileRemoved="fileRemoved"
						@fileSuccess="fileSuccess"
						@overSize="overSizeHandler"
						accept=".pdf, .doc, .docx, .xls, .xlsx, .txt"
						:multiple="true"
						:limits="1"
						:maxSize="20971520"
						:allowDuplicateUploads="false"
						@deleteFile="onFileDelete"
						ref="contractUpload"
					>
						<div slot="upload-btn">
							<div class="slot_btn">选择附件</div>
						</div>
					</lessoUploader>
					<div v-if="files.length>0">
						<div
							class="uploaded_files"
							v-for="(file,index) in files"
							:key="index"
							@mouseenter="file.iconShow=true"
							@mouseleave="file.iconShow=false"
						>
							<div class="name" :title="file.name">
								<i class="el-icon-document"></i>
								{{file.name}}
							</div>
							<span class="state_icon">
								<i class="el-icon-circle-check" style="color:#67c23a" v-show="!file.iconShow"></i>
								<i class="el-icon-close" v-show="file.iconShow" @click="deletedFile(file)"></i>
							</span>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="备注信息" placeholder="请输入备注信息" prop="remark">
					<el-input
						v-model="ruleForm.remark"
						type="textarea"
						maxlength="200"
						placeholder="请输入备注信息,最多支持200字符!"
						clearable
					></el-input>
				</el-form-item>
			</el-form>

			<span slot="footer" class="dialog-footer">
				<el-button @click="cancel" :disabled.sync="disState">取消</el-button>
				<el-button type="primary" @click="saveData('1')" :disabled.sync="disState">保存</el-button>
				<el-button type="primary" @click="saveData('2')" :disabled.sync="disState" v-if="btnShow">保存并继续</el-button>
			</span>
		</el-dialog>

		<el-dialog
			title="供应商信息"
			:visible.sync="srmSupplierDialogVisible"
			width="50%"
			:before-close="srmSupplierDialogClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<srmSupplierInfo ref="srmSupplierInfo" :layout="layout" @setSrmSupplierInfo="setSrmSupplierInfo"></srmSupplierInfo>
			<!--@setSapSupplierCompanyInfo="getSelectedCompany" :setSelectedSupplierCode="getSelectedSupplierCode"-->
		</el-dialog>
		<!-- 合同导入弹窗 -->
		<el-dialog
			title="导入合同模板"
			v-if="importDialogVisible"
			:visible.sync="importDialogVisible"
			width="50%"
			:before-close="importHandleClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<importFile
				:moduleName="moduleName"
				@setImportData="getImportData"
				:closeImportDialog="importDialogVisible"
				:tempUrl="tempUrl"
			></importFile>
			<span slot="footer" class="dialog-footer">
				<el-button @click="importHandleClose">取消</el-button>
				<el-button type="primary" @click="saveImportData" :loading="btn_loading">导入</el-button>
			</span>
		</el-dialog>
		<!-- 查看合同 -->
		<contract-details
			:dialogVisible="detailsVisible"
			:detailsForm="detailsForm"
			@closeDialog="detailsVisible=false"
			@downlaodFile="downLoadFile"
			v-if="detailsVisible"
		></contract-details>
	</div>
</template>

<script>
import _Api from "@/api"
import localeText from "@/i18n/agGridText"
import constant from "@/public/constant"
import Vue from "vue"
import srmSupplierInfo from "@/components/srmSupplierInfo.vue"
import importFile from "@/components/importFile.js"
import downLoadFileFunc from "@/public/downLoadFile"
import Msg from "@/public/message"
import fileStream from "@/public/fileStream.js"
import ContractDetailsDialog from "./common/contractDetailsDialog"
import lessoUploader from 'lesso-file-upload/lessoUploader'
import apienv from '@/api/env'
import gridOptions from 'lesso-common/public/gridOptions';

const details = Vue.extend({
	template: '<el-button type="text" @click="details" class="rendererClass" size="mini">附件名称</el-button>',
	methods: {
		details () {
			this.params.context.componentParent.showDifDialog(this.params.node.data);
		}
	}
})

export default {

	data () {
		var checkContractNo = (rule, value, callback) => {
			setTimeout(() => {
				if (value == '') {
					callback(new Error("请输入合同编号!"));
				}
				else
					callback();
			}, 100);
		};

		var checkContractName = (rule, value, callback) => {
			setTimeout(() => {
				if (value == '') {
					callback(new Error("请输入合同名称！"));
				}
				else
					callback();
			}, 100);
		};

		var checkSelCompany = (rule, value, callback) => {
			setTimeout(() => {
				if (value == '') {
					callback(new Error("请输入公司名称！"));
				}
				else
					callback();
			}, 100);
		};

		var checkStartDate = (rule, value, callback) => {
			setTimeout(() => {
				if (value == '') {
					callback(new Error("请输入有效日期！"));
				}
				else
					callback();
			}, 100);
		};

		return {
			comOptions: [],
			cusOptions: [],
			selCompanyCode: "",
			selCusCode: "",
			contractNo: "",
			purOrdNo: "",//采购订单号
			startDate: "",
			endDate: "",
			remark: "",
			billState: "0",
			total: 0,
			cdisabled: false,
			sdisabled: false,
			currentPage: 0,
			pageSize: 30,
			btn_add_Disabled: false,
			btn_edit_Disabled: false,
			btn_reuse_Disabled: false,
			disState: false,
			inputDis: false,   //是否只读
			Ccommpany: false,
			Csupplier: false,
			dialogVisible: false,//弹出框的可视状态
			rowData: [],//行
			columnDefs: [],//列
			loading: false,//加载
			btnShow2: true,
			reShow1: true,
			btnShow: false,
			radio: 0,
			upload: "",
			//弹出框
			title: "",//弹出框的标题
			mode: "",
			fileList: [],//上传文件
			ruleForm: {},
			upload_url: this.$uploadUrl,
			btn_upload_dis: false,
			upload_show: false,
			selCus: {},
			selCus1: {},
			selCusName: "",
			srmSupplierDialogVisible: false,
			inputClearBut: false,
			layout: {},
			layoutForm: {},
			rules: {
				contractNo: [{
					validator: checkContractNo,
					trigger: "change"
				}, {
					required: true,
					message: "请输入合同编号！",
					trigger: "blur"
				}],

				contractName: [{
					validator: checkContractName,
					trigger: "change"
				}, {
					required: true,
					message: "请输入合同名称！",
					trigger: "blur"
				}],

				selCompany: [{
					validator: checkSelCompany,
					trigger: "change"
				}, {
					required: true,
					message: "请输入公司名称！",
					trigger: "blur"
				}],

				// selCusName: [{
				//   required: true,
				//   message: "供应商名称不能为空",
				//   validator:checkSelCusName,
				//   // message: "请输入供应商名称！",
				//   trigger: "change"
				// }],

				startDate: [{
					validator: checkStartDate,
					trigger: "change"
				}, {
					required: true,
					message: "请输入有效日期！",
					trigger: "blur"
				}]
			},
			//   文件上传地址
			baseUrl: apienv[constant.appenv].srm + 'uploadFastdfs/',
			userInfo: {
				userName: this.$global.user.employeeName,
				userId: this.$global.user.id,
				groupName: 'SRM'
			},
			//   合同批量导入
			importDialogVisible: false,
			moduleName: 'contract',
			importData: [],
			btn_loading: false,
			tempUrl: '', //合同模板线上下载地址
			// 操作按钮权限控制
			btnAuthList: [],
			//  合同详情弹出框可视状态
			detailsVisible: false,
			detailsForm: {},
			//  已上传
			files: []
		}
	},
	components: {
		srmSupplierInfo,
		importFile,
		'contract-details': ContractDetailsDialog,
		lessoUploader
	},
	beforeMount () {
		this.gridOptions = Object.assign({
			context: {
				componentParent: this
			},
			rowSelection: "multiple",
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true
		}, gridOptions())



		this.columnDefs = [
			{ headerName: "合同编号", field: "contractNo", width: 130, checkboxSelection: true, headerCheckboxSelection: true, headerCheckboxSelectionFilteredOnly: true },
			{ headerName: "合同名称", field: "contractName", width: 200 },
			{ headerName: "公司名称", field: "companyName", width: 250 },
			{ headerName: "供应商名称", field: "supplierName", width: 250 },
			{
				headerName: "开始日期",
				field: "startDate",
				width: 120,
				cellRenderer: function (params) {
					if (params.value) {
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
					}
				}
			},
			{
				headerName: "结束日期",
				field: "endDate",
				width: 120,
				cellRenderer: function (params) {
					if (params.value) {
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
					}
				}
			},
			{ headerName: "备注", field: "remark", width: 120 },
			{
				headerName: "状态",
				field: "billState",
				width: 120,
				cellRenderer: function (params) {
					var str = '';
					if (params.value == 0) {
						str = '未审核';
					} else {
						str = '已审核';
					}
					return `<span>${str}</span>`
				}
			},
			{ headerName: "创建人", field: "creator", width: 150 },
			{ headerName: "创建日期", field: "createDate", width: 150 },
			{ headerName: "审核人", field: "auditor", width: 120 },
			{ headerName: "审核日期", field: "auditDate", width: 150 },

		];
	},
	mounted () {
		this.getBtAuth()
		this.getAuthInfo();
		this.search(1);
		this.getContractTemp()
	},
	methods: {
		//   查看合同详情
		viewDetail () {
			let row = this.gridOptions.api.getSelectedRows()
			if (row.length <= 0) {
				this.$alert("提示：请选择需要查看的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			if (row.length > 1) {
				this.$alert("提示：只能选择单条数据进行查看！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			this.detailsForm = row[0]
			this.detailsVisible = true
		},
		mounseLeave () {
			if (this.selCusName != "")
				this.inputClearBut = false;
		},
		mouseEnter () {
			if (this.selCusName != "")
				this.inputClearBut = true;
		},
		inputClearSon () {
			this.selCusCode = "";
			this.selCusName = "";
			this.selCus.supplierCode = ""
			this.inputClearBut = false;
		},
		setSrmSupplierInfo (msg) {
			if (msg.length > 0) {
				this.srmSupplierDialogVisible = false;
				// this.selCusCode = msg[0].id;
				if (this.dialogVisible == false) {
					this.selCusName = msg[0].supplierName;
					this.selCus = msg[0];
				}
				else {
					this.ruleForm.selCusName = msg[0].supplierName;
					this.selCus1 = msg[0];
				}


				// this.inputClearBut = true;
			}
		},

		srmSupplierDialogClose (done) {
			done();
		},
		showSupplierDialog () {
			var that = this;
			this.layout.companyCode = this.selCompanyCode
			if (!this.layout.companyCode) {
				this.$alert("提示：请选择公司！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				this.$refs.content.focus();
				return;
			} else {
				this.srmSupplierDialogVisible = true;
				this.$nextTick(_ => {
					that.$refs.srmSupplierInfo.search();
				});

				// 	setTimeout(()=>{
				// 	that.$refs.srmSupplierInfo.search();
				// },50)
			}
		},

		showSupplierDialogOther () {
			var that = this;
			if (!this.ruleForm.selCompany) {
				this.$alert("提示：请选择公司！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				this.$refs.content.focus();
				return;
			} else {
				this.srmSupplierDialogVisible = true;
				this.$nextTick(_ => {
					that.$refs.srmSupplierInfo.search();
				});
			}

		},

		changeradio (radio) {
			if (radio == '0') {
				this.billState = "0";
			}
			else {
				this.billState = "2";

			}
			this.search(1);
		},
		// 新增合同
		add () {
			if (this.$refs.ruleForm) {
				// this.$refs.ruleForm.clearValidate();
			}
			this.files = []
			this.btnShow = true;
			this.Csupplier = true;
			this.Ccommpany = true;
			this.cdisabled = false;
			this.sdisabled = false;
			this.title = "新增合同";
			this.ruleForm = {}
			this.inputDis = false;
			this.mode = "add";
			this.dialogVisible = true;
		},
		// 编辑合同
		edit () {
			var row = this.gridOptions.api.getSelectedRows();
			this.files = []
			if (row.length <= 0) {
				this.$alert("提示：请选择需要编辑的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			if (row.length > 1) {
				this.$alert("提示：只能选择单条数据进行编辑操作！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			this.title = "编辑合同";
			this.btnShow = false;
			this.ruleForm = row[0];
			this.ruleForm.selCompany = row[0].companyCode;
			this.ruleForm.selCusName = row[0].supplierName;
			// this.ruleForm.s
			// this.fileList[0].name=row[0].attachmentName;
			// this.fileList.url=row[0].url;
			if (row[0].url != "") {
				this.files = [{
					name: row[0].attachmentName,
					url: row[0].url,
					md5: row[0].md5 || '123',
					iconShow: false
				}].splice(0);
			}
			this.fileList = this.files
			this.selCus1.supplierCode = row[0].supplierCode
			this.selCus1.id = row[0].supplierId;
			this.layoutForm.companyCode = row[0].companyCode;
			this.inputDis = true;
			this.Csupplier = false;
			this.Ccommpany = false;
			this.cdisabled = true;
			this.sdisabled = true;
			this.mode = "edit";
			var that = this;
			this.$nextTick(_ => {
				// that.$refs.ruleForm.clearValidate();
			});
			this.mode = "edit";
			this.dialogVisible = true;

		},
		/*type:2：审核，0：弃审*/
		reviewContract (type) {
			var row = this.gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				this.$alert("提示：请选择需要审核/弃审的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			var that = this;
			that.$confirm("是否确认审核/弃审该数据？", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				var id = '';
				for (var i = 0; i < row.length; i++) {
					id += row[i].id + ',';
				}
				id = id.substr(0, id.length - 1);
				var obj = {
					id: id,
					auditor: this.$global.user.loginName,
					auditorId: this.$global.user.id,
					auditState: type
				};

				_Api.reviewContract(obj).then(function (response) {
					var data = response.data;
					if (data.code == "1") {
						that.$message({
							message: "操作成功",
							type: "success"
						});

						that.search(1);

					} else {
						that.$alert(response.data.info, {
							showClose: false,
							confirmButton: "确定",
							customClass: "alertFailure"
						});
					}
				})

			}).catch(() => { })
			//   that.search();
		},
		// 选择公司下拉框回调
		companyChange (value) {
			//公司下拉框选择
			if (value) {
				var obj = {
					name: value
				};
				var that = this;
				this.layout.companyCode = value;
				this.layout.auth = true;
				this.layoutForm.companyCode = value;
				this.layoutForm.auth = true;
				_Api.getAuthSupplierByCompanyCode(obj).then(function (response) {
					var data = response.data;
					if (data.code == "1") {
						if (data.total > 0)
							that.cusOptions = data.rows;
						else
							that.cusOptions = [];
					}
				}).catch((err) => {
					that.$alert(err.data.message, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					});
					that.cusOptions = [];
				})
			} else {
				this.getAuthInfo();
			}
		},
		getAuthInfo () {
			//获取当前账号权限公司
			var obj = {};
			if (this.$global.user.userTypeId == 4) {
				obj.account = this.$global.user.userName;
				obj.userType = 2;
			}
			else if (this.$global.user.userTypeId == 1) {
				obj.account = this.$global.user.oaNum;
				obj.userType = 1;
			}
			var that = this;
			_Api.getAuthInfo(obj).then(function (response) {
				var data = response.data;
				if (data.code == "1") {
					that.comOptions = data.rows.myMstCompany;
					that.cusOptions = data.rows.myMstSupplier;
				} else {
					that.comOptions = [];
					that.cusOptions = [];
				}
			}).catch((err) => {
				that.$alert(err.data.message, {
					showClose: false,
					confirmButton: "确定",
					customClass: "alertFailure"
				});
				that.comOptions = [];
				that.cusOptions = [];
			})
		},
		// 查询列表数据
		search (flag) {
			if (flag) { this.currentPage = 1 }
			var obj = {
				eqParams: {},
				likeParams: {},
				current: this.currentPage,
				size: this.pageSize
			};
			if (this.contractNo.replace(/\s+/g, "") == "")
				;
			else
				obj.likeParams.contractNo = this.contractNo.replace(/\s+/g, "");//去掉文本框里的空格	
			if (this.selCompanyCode)
				obj.eqParams.companyCode = this.selCompanyCode;
			if (this.selCus != null)
				obj.eqParams.supplierCode = this.selCus.supplierCode;
			obj.eqParams.billState = this.billState;
			this.obj = obj;
			var that = this;
			this.loading = true;
			_Api.getContractList(obj).then(function (response) {

				var data = response.data;
				if (data.code == "1") {
					if (data.total >= 0) {
						if (data.rows != null) {
							that.gridOptions.api.setRowData(data.rows);
							that.loading = false;
							that.total = data.total;
						}
					}
				}
				else {
					that.loading = false;
					that.$alert(data.info, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					});
				}
			}).catch((err) => {
				that.loading = false;
				Msg.showErrorMsg(err.data.message);
			})
		},
		//选择分页重新回填数据
		paginationFillCondition (type) {
			this.search(type);
		},
		//处理分页的四个函数
		handleSizeChange (val) {
			this.pageSize = val;
			this.paginationFillCondition(1);
		},
		handleCurrentChange (val) {
			this.currentPage = val;
			this.paginationFillCondition(0);
		},
		handlePrevClick (params) {
			this.currentPage = params;
			this.paginationFillCondition(0);
		},
		handleNextClick (params) {
			this.currentPage = params;
			this.paginationFillCondition(0);
		},
		// 关闭新增合同弹窗
		handleClose (done) {
			var that = this;
			this.fileList = [];
			this.files = []
			this.dialogVisible = false
			this.$nextTick(_ => {
				that.$refs.ruleForm.clearValidate();
			});
			done();
			this.search(1);
		},
		// 手动触发上传
		submitUpload () {
			this.$refs.upload.submit();
		},
		// 文件移除时钩子
		handleRemove (file, fileList) {
			this.fileList = fileList;
		},
		// 点击已上传文件钩子
		handlePreview (file) {
			this.downLoadFile(file);
		},
		// 文件超出上传个数限制
		handleExceed (file, fileList) {
			this.$message.warning(`最多可添加 1 个附件`);
		},
		// 文件删除之前钩子
		beforeRemove (file, fileList) {
		},
		// 文件状态改变钩子
		upload_change (file, fileList) {
			//   this.upload_url = constant.upload_url;
			//   this.filename = file.name;
			//   this.fileList = fileList;
		},
		/* 文件上传成功钩子
		* response 成功返回得文件对象
		* file 上传得文件信息
		* fileList 
		*/
		uploadSuccess (response, file, fileList) {
			this.fileList = []
			if (response.code == 1) {
				this.$message({
					message: "上传成功",
					type: "success"
				});
				//保存文件信息
				const { orgName, fileName } = response.rows[0]
				this.fileList.push({
					name: orgName,
					url: fileName
				});
				this.difDetailInfo = response.rows[0];
			} else {
				this.$alert("请求失败", {
					showClose: false,
					confirmButton: "确定",
					customClass: "alertFailure"
				});
				this.$refs.upload.clearFiles();
			}
		},
		// 上传文件前对文件大小格式进行校验
		beforeAvatarUpload (file) {
			var fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
			if (fileType != "txt" && fileType != "pdf" && fileType != "doc" && fileType != "docx" && fileType != "xls" && fileType != "xlsx") {
				this.$message({
					message: '上传文件类型只支持.txt/.pdf/.doc/.docx/.xls/.xlsx！',
					type: 'warning'
				});
				return false;
			}
			const size = file.size / 1024 / 1024 < 20;
			if (!size) {
				this.$message({
					message: '上传模板大小不能超过 20MB!',
					type: 'warning'
				});
				return false;
			}
		},
		// 文件通过检查回调
		fileAdded (file) {
			for (var i in this.fileList) {
				if (this.fileList[i].md5 == file.md5)
					file.cancel()
			}
			this.files = []
			this.fileList = []
		},
		// 删除文件
		onFileDelete (file, callback) {
			var that = this;
			this.$confirm("是否删除该附件？", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				// if (that.mode == "add") {
				callback(true);
				for (var i in that.fileList) {
					if (that.fileList[i].md5 == file.md5) {
						that.fileList.splice(i, 1);
					}
				}
				// }
			}).catch(() => { })
		},
		// 编辑时删除文件
		deletedFile (file, index) {
			this.$confirm("是否删除该附件？", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				let obj = {
					groupName: 'SRM',
					fileMd5: file.md5,
					uid: this.$global.user.id
				}
				_Api.deletedFastdfsFile(obj).then(({ data }) => {
					if (data.code == 200) {
						Msg.showSuccessMsg('文件已删除')
						this.fileList.splice(index, 1)
					} else {
						Msg.showErrorMsg(data.msg)
					}
				}).catch(err => {
					Msg.showErrorMsg(err.data.message)
				})
			})
		},
		// 文件上传成功回调
		fileSuccess (file, message, chunk) {
			if (message.code === 200) {
				var obj = {
					creator: this.$global.user.loginName,
					creatorId: this.$global.user.id,
					resourceType: 1
				};
				obj.size = file.size;
				obj.url = file.viewPath;
				obj.md5 = file.md5;
				obj.name = file.name;
				this.fileList.push(obj);
			}
		},

		fileRemoved (file, response) {
			if (response.code === 200) {
				for (let i = this.fileList.length - 1; i >= 0; i--) {
					if (this.fileList[i].md5 == file.md5)
						this.fileList.splice(i, 1);
				}
			}
		},
		// 文件超出大小回调
		overSizeHandler (file) { // 文件过大回调
			this.$message.warning("选择的文件大小不能超过20M")
		},
		//文件类型不合法
		onInvalidFile (file) {
			this.$message.warning('上传文件类型只支持.pdf/.doc/.docx/.xls/.xlsx/.txt')
		},
		// 文件上传失败回调
		fileError (file, message, chunk) {
			message = JSON.parse(message)
			this.$message.error(message.msg);
		},
		//文件个数超出限制
		fileExceed (files, fileList) {
			this.$message.warning('上传文件个数超出限制,最多只能上传1个文件')
		},
		// 新增或编辑合同后进行保存
		saveData (state) {
			if (this.mode == "add") {//新增页面,insert
				this.$refs["ruleForm"].validate((valid) => {
					if (valid == false) {
						return false;
					}

					var that = this;
					var obj = {};
					this.ruleForm.endDate = this.ruleForm.endDate + ' 23:59:59';
					if (this.ruleForm.startDate > this.ruleForm.endDate && this.ruleForm.endDate) {
						this.$alert("提示：开始日期不能大于结束日期", {
							showClose: false,
							confirmButtonText: "确定",
							customClass: "alertPrompt"
						});
						return;
					}
					if (!this.ruleForm.selCusName) {
						this.$alert("提示：请选择供应商", {
							showClose: false,
							confirmButtonText: "确定",
							customClass: "alertPrompt"
						});
						return;
					}
					obj.id = ""//主键
					obj.contractNo = this.ruleForm.contractNo;//合同编号
					obj.contractName = this.ruleForm.contractName;//合同名称
					obj.supplierId = this.selCus1.id;//供应商id
					obj.companyCode = this.ruleForm.selCompany;//公司编码
					obj.startDate = this.ruleForm.startDate;//开始时间
					obj.endDate = this.ruleForm.endDate;//结束时间
					obj.remark = this.ruleForm.remark;//备注信息
					obj.billState = "0";
					obj.supplierCode = this.selCus1.supplierCode;
					this.comOptions.forEach(function (item) {
						if (item.companyCode == obj.companyCode) {
							obj.companyId = item.id;

						}
					});
					if (this.fileList == "" || this.fileList == null) {
						obj.attachmentName = '';
						obj.url = '';
					}
					else {
						obj.attachmentName = this.fileList[0].name;
						obj.url = this.fileList[0].url;
					}

					obj.creatorId = this.$global.user.id;//创建人ID
					obj.creator = this.$global.user.employeeName;//创建人
					let params = []
					params.push(obj)
					_Api.saveContract(params).then(function (response) {
						var data = response.data;

						if (data.code == "1") {
							that.$message({
								message: "保存成功",
								type: "success"
							});
							if (state === '1') {
								that.cancel()
							} else if (state === '2') {
								that.saveDataAgain()
							}
							that.layoutForm.companyCode = "";
							that.search(1);
						}
						else {
							that.layoutForm.companyCode = "";
							that.$alert(data.info, {
								showClose: false,
								confirmButton: "确定",
								customClass: "alertFailure"							});
						}
					})
						.catch(() => {
							that.layoutForm.companyCode = "";
							that.$alert("请求失败！", {
								showClose: false,
								confirmButton: "确定",
								customClass: "alertFailure"							});
						});
				});


			}
			else {//编辑页面
				this.$refs["ruleForm"].validate((valid) => {
					if (valid == false) {
						return false;
					}
					var that = this;
					var obj = {};
					obj.id = this.ruleForm.id//主键
					obj.contractNo = this.ruleForm.contractNo;//合同编号
					obj.contractName = this.ruleForm.contractName;//合同名称
					// obj.supplierId = this.ruleForm.selCusName;//供应商id
					// obj.supplierCode = this.ruleForm.selCusName.supplierCode;//供应商编码
					obj.supplierId = this.selCus1.id;//供应商idselCus
					obj.supplierCode = this.selCus1.supplierCode;//供应商编码
					//obj.companyId = this.ruleForm.selCompany;//公司id
					obj.companyCode = this.ruleForm.selCompany;//公司编码
					obj.startDate = this.ruleForm.startDate;//开始时间
					obj.endDate = this.ruleForm.endDate;//结束时间
					obj.remark = this.ruleForm.remark;//备注信息
					obj.billState = "0";

					this.comOptions.forEach(function (item) {
						if (item.companyCode == obj.companyCode) {
							obj.companyId = item.id;

						}
					});
					if (this.fileList == "" || this.fileList == null) {
						obj.attachmentName = '';
						obj.url = '';
					}
					else {
						obj.attachmentName = this.fileList[0].name;
						obj.url = this.fileList[0].url;
						obj.md5 = this.fileList[0].md5;
					}
					obj.modifyerId = this.$global.user.id;//修改人ID
					obj.modifyer = this.$global.user.employeeName;//修改人
					let params = []
					params.push(obj)
					_Api.saveContract(params).then(function (response) {
						var data = response.data;
						if (data.code == "1") {
							that.$message({
								message: "保存成功",
								type: "success"
							});
							that.cancel()
							that.search(1);
							that.fileList = [];
						}
						else {
							that.$alert(data.info, {
								showClose: false,
								confirmButton: "确定",
								customClass: "alertFailure"
							});
						}
					})
						.catch((a, b, c) => {
							//this.layout.companyCode="";
							that.$alert("保存失败，请检查网络！", {
								showClose: false,
								confirmButton: "确定",
								customClass: "alertFailure"
							});
						});
				})

			}
		},
		// 保存后继续添加新的合同
		saveDataAgain () {
			// this.saveData();
			this.btnShow = true;
			this.Csupplier = true;
			this.Ccommpany = true;
			this.cdisabled = false;
			this.sdisabled = false;
			this.title = "新增合同";
			this.$refs['contractUpload'].initFileList()
			this.$set(this.ruleForm, 'contractNo', '');
			this.$set(this.ruleForm, 'contractName', '');
			this.$set(this.ruleForm, 'selCusName', '');
			this.$set(this.ruleForm, 'selCompany', '');
			this.$set(this.ruleForm, 'startDate', '');
			this.$set(this.ruleForm, 'endDate', '');
			this.$set(this.ruleForm, 'remark', '');
			this.fileList = [];
			// this.dialogVisible = true;
		},
		// 取消按钮关闭弹窗重置表单信息
		cancel () {
			//   var that = this;
			this.dialogVisible = false;
			this.fileList = []
			this.$nextTick(_ => {
				// that.$refs.ruleForm.clearValidate();
			})
			this.ruleForm = {}
			this.search(1);
		},
		// 下载文件
		downLoadFile (item) {
			var group = ''
			if (item.url.indexOf('SRM') > -1) {
				group = 'SRM'
			} else if (item.url.indexOf('SIGN') > -1) {
				group = 'SIGN'
			} else if (item.url.indexOf('TEST') > -1) {
				group = 'TEST'
			} else if (item.url.indexOf('MES') > -1) {
				group = 'MES'
			}
			var obj = {
				viewPath: item.url,
				groupName: group,
				fileName: ''
			};
			downLoadFileFunc(obj, item.name)
		},
		// 创建a标签下载文件
		downLoad (filename, url) {
			var eleLink = document.createElement('a');
			eleLink.style.display = 'none';
			eleLink.setAttribute("href", url);   //文件下载地址
			eleLink.setAttribute("download", filename);  //download属性只能在同域实现
			// 触发点击
			document.body.appendChild(eleLink);
			eleLink.click();
			// 然后移除
			document.body.removeChild(eleLink);
		},

		showCallback () {
			this.$refs.ruleForm.clearValidate()
		},
		// 关闭导入模板弹窗
		importHandleClose (done) {
			//   done();
			this.importDialogVisible = false;
		},
		// 打开导入模板弹窗
		openImportDialog () {
			this.importDialogVisible = true
		},
		// 获取导入数据
		getImportData (val) {
			this.importData = val
			console.log(val,'获取导入数据--22')
		},
		// 确认保存数据
		saveImportData () {
			if (this.importData.length == 0) {
				this.$alert("导入数据为空！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			for (let i in this.importData) {
				this.importData[i].creator = this.$global.user.employeeName
				this.importData[i].creatorId = this.$global.user.id
				this.importData[i].id = ""
				this.importData[i].billState = "0"
				this.importData[i].startDate = new Date(this.importData[i].startDate).Format("yyyy-MM-dd 00:00:00")
				this.importData[i].endDate = new Date(this.importData[i].endDate).Format("yyyy-MM-dd 00:00:00")
			}
			this.btn_loading = true
			_Api.saveContract(this.importData).then((response) => {
				let data = response.data
				this.btn_loading = false
				if (data.code == "1") {
					this.$message({
						message: "保存成功",
						type: "success"
					})
					this.importHandleClose()
					this.search(1);
				}
				else {
					this.$alert(data.info, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					})
				}
			})
				.catch((err) => {
					this.btn_loading = false
					this.$alert(err.data.message, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					})
				})
		},
		// 获取合同导入模板
		getContractTemp () {
			fileStream.getPrintTempUrl("contract").then(url => {
			
				this.tempUrl = url
				
			})
		},
		// 获取按钮权限列表
		getBtAuth () {
			var that = this;
			var obj = {
				resultType: "0",
				code: 'contractManager',
				authClientCode: constant.authCode.code,
				authTenantCode: constant.authCode.tcode
			};
			_Api.getUserAuthMenu(obj).then(function (response) {
				var data = response.data;
				if (data.code == "1") {
					if (data.total > 0) {
						data.rows.forEach(item => {
							that.btnAuthList.push(item.code)
						})
					}
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch((err) => {
				Msg.showErrorMsg(err.data.message);
			})
		},
	}
}


</script>
